﻿/*
ChangeTracking (a library for POCO change tracking).

Copyright (C) 2014 Dmitry Merzagitovich Arslanov

This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free
Software Foundation; either version 2.1 of the License, or (at your option) any
later version.

This library is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*/

using System;
using System.Collections;
using System.Reflection;

namespace ChangeTracking
{
    /// <summary>
    /// Describes one-to-many relation between several object instances:
    /// one parent and many of children.
    /// </summary>
    public sealed class ListProperty : Property
    {
        /// <summary>
        /// Index of child in list of children.
        /// </summary>
        public int Index { get; private set; }

        /// <summary>
        /// List of children.
        /// </summary>
        public IList List { get; private set; }

        internal ListProperty(PropertyInfo info, IList list, int index)
            : base(info)
        {
            List = list;
            Index = index;
        }

        /// <summary>
        /// Indicates whether the current object is equal to another object of
        /// the same type.
        /// </summary>
        /// <param name="other">An object to compare with this object.</param>
        /// <returns>
        /// True if the current object is equal to the other parameter;
        /// otherwise, false.
        /// </returns>
        public override bool Equals(Property other)
        {
            ListProperty listProperty = other as ListProperty;
            if (listProperty == null) return false;
            return Info == listProperty.Info &&
                   Index == listProperty.Index;
        }

        /// <summary>
        /// Serves as the default hash function.
        /// </summary>
        /// <returns>A hash code for the current object.</returns>
        public override int GetHashCode()
        {
            int baseHashCode = base.GetHashCode();
            Tuple<int, int> tuple = new Tuple<int, int>(baseHashCode, Index);
            return tuple.GetHashCode();
        }

        /// <summary>
        /// Returns a string that represents the current object.
        /// </summary>
        /// <returns>A string that represents the current object.</returns>
        public override string ToString()
        {
            return string.Format("{0}:{1}", Info.Name, Index);
        }
    }
}
